package com.app.service.impl.article;

import com.app.domain.po.article.ArticleContentPo;
import com.app.domain.vo.article.ArticleContentVo;
import com.app.framework.utils.CoBeanUtils;
import com.app.mapper.article.ArticleContentMapper;
import com.app.service.article.ArticleContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * 文章内容方法实现
 */
@Service
public class ArticleContentServiceImpl extends ServiceImpl<ArticleContentMapper, ArticleContentPo> implements ArticleContentService {

    /**
     * 获取文章内容
     *
     * @param articleId 文章ID
     */
    @Override
    @Cacheable(cacheNames = "article_content", key = "#articleId")
    public ArticleContentVo selectArticleContent(Long articleId) {
        ArticleContentVo articleContentVo = baseMapper.selectArticleContent(articleId);
        Assert.notNull(articleContentVo, "文章内容不存在");
        return articleContentVo;
    }

    /**
     * 添加文章内容
     *
     * @param articleId 文章ID
     * @param content   文章内容
     * @param contentMd markdown版的章内容
     */
    @Override
    public void saveOne(Long articleId, String content, String contentMd) {
        ArticleContentPo articleContentPo = new ArticleContentPo();
        articleContentPo.setArticleId(articleId);
        articleContentPo.setContent(content);
        articleContentPo.setContentMd(contentMd);
        articleContentPo.setCreateTime(new Date());
        baseMapper.insert(articleContentPo);
    }

    /**
     * 修改文章内容
     *
     * @param articleId 文章ID
     * @param content   文章内容
     * @param contentMd markdown版的章内容
     */
    @Override
    @CacheEvict(cacheNames = "article_content", key = "#articleId")
    public void updateOne(Long articleId, String content, String contentMd) {
        ArticleContentVo articleContentVo = baseMapper.selectArticleContent(articleId);
        ArticleContentPo articleContentPo = CoBeanUtils.copy(articleContentVo, ArticleContentPo.class);
        Assert.notNull(articleContentPo, "文章内容不存在");
        articleContentPo.setContent(content);
        articleContentPo.setContentMd(contentMd);
        articleContentPo.setUpdateTime(new Date());
        baseMapper.updateById(articleContentPo);
    }

}